using System;
using System.Runtime.InteropServices;

namespace svs.Mobile.BeyondMedia.UiCore.GDI
{
	public class HrException : Exception
	{
		private uint m_hr;

		public HrException(uint hr)
		{
			m_hr = hr;
		}

		public HrException(int hr)
		{
			m_hr = (uint) hr;
		}

		public new uint HResult
		{
			get { return m_hr; }
		}
	}

	public class Win32Exception : Exception
	{
		private readonly int m_error;

		public Win32Exception(int error)
		{
			m_error = error;
		}

		public override string Message
		{
			get { return ErrorLookup.Message(m_error); }
		}

		public int Code
		{
			get { return m_error; }
		}
	}

	/// <summary>
	/// Summary description for ErrorLookup.
	/// </summary>
	internal class ErrorLookup
	{
		public static string Message(int hr)
		{
			return Message((uint) hr);
		}

		public static string Message(uint hr)
		{
			string buffer = new string(' ', 256);
			int num = FormatMessage(EFormatMessage.FROM_SYSTEM, 0, hr, 0, buffer, buffer.Length, null);
			if (num == 0)
				return String.Empty;
			else
				return buffer.Substring(0, num);
		}

		private enum EFormatMessage
		{
			ALLOCATE_BUFFER	= 0x00000100,
			IGNORE_INSERTS	= 0x00000200,
			FROM_STRING		= 0x00000400,
			FROM_HMODULE	= 0x00000800,
			FROM_SYSTEM		= 0x00001000,
			ARGUMENT_ARRAY  = 0x00002000,
			MAX_WIDTH_MASK	= 0x000000FF,
		}

		[ DllImport("coredll") ]
		private static extern int FormatMessage(EFormatMessage flags, uint lpSource, uint dwMessageId, uint dwLanguageId, string buffer, int nSize, object args);
	}
}